package com.alquimia.identityaccess.domain.model;



import com.alquimia.domain.Identificador;

import java.io.Serializable;

/**
 * Created by Ivo on 12/07/2014.
 */
public class User extends Identificador implements Serializable {

    private UserId userId;
    private String username;
    private String password;
    private Person person;


    public User(UserId aUserId, String aUsername, String aPassword, Person aPerson) {

        this();

        setUsername(aUsername);
        setPassword(aPassword);
        setPerson(aPerson);
        setUserId(aUserId);

        aPerson.internalOnlySetUser(this);

    }

    public void changePassword(String aPassword) {
        this.setPassword(aPassword);
    }

    public void changeFullName(FullName aFullName) {
        this.person().changeFullName(aFullName);
    }

    public void changeEmailAddress(EmailAddress aEmailAddress) {
        this.person().changeEmailAddress(aEmailAddress);
    }

    protected User() {
        super();
    }

    public String username() {
        return this.username;
    }

    public String password() {
        return this.password;
    }

    public Person person() {
        return this.person;
    }

    public UserId userId() {
        return this.userId;
    }

    private void setPerson(Person aPerson) {
        if (aPerson == null)
            throw new NullPointerException("La person no puede ser nula.");

        this.person = aPerson;

    }

    private void setUsername(String aUsername) {

        if (aUsername.isEmpty())
            throw new IllegalArgumentException("Se requiere el firstName.");

        if (aUsername.length() < 3 || aUsername.length() > 100)
            throw new IllegalArgumentException("El firstName de user debe tener al menos tres 3 letras y no mas de 100.");

        this.username = aUsername;

    }

    private void setPassword(String aPassword) {

        if (aPassword.isEmpty())
            throw new IllegalArgumentException("La password es requerida.");

        if (aPassword.length() < 8 || aPassword.length() > 100)
            throw new IllegalArgumentException("La password debe tener al menos tres 8 letras y no mas de 100.");

        this.password = aPassword;
    }

    private void setUserId(UserId aUserId) {

        if (aUserId == null)
            throw new NullPointerException("El user id no debe ser nulo.");

        this.userId = aUserId;
    }

    public UserDescriptor userDescriptor() {

        return new UserDescriptor(
                this.userId,
                this.username(),
                this.person().emailAddress().address());
    }
}
